const express = require("express");
const mongoose = require("mongoose");

const Car = require("../../models/Car");
const Collect = require("../../models/Collect");

const router = express.Router({
  mergeParams: true,
});

// =============================================
// 创建车辆
router.post("/car/create", async (req, res) => {
  const model = await Car.create(req.body);
  res.send(model);
});

// 分页查询汽车列表
router.get("/car", async (req, res) => {
  // console.log(req.query);
  const currentPage = req.query.currentPage ? Number(req.query.currentPage) : 1;
  const pageSize = req.query.pageSize ? Number(req.query.pageSize) : 10;
  const orderByTime = Number(req.query.orderByTime) == 1 ? 1 : -1;

  // const searchKey = req.query.searchKey;
  // var re = new RegExp(searchKey, "i");
  // 其他信息
  const brand = req.query.brand;
  const carModel = req.query.carModel;
  const color = req.query.color;
  const fuelType = req.query.fuelType;

  matchOptions = {};
  if (brand != "") {
    matchOptions.brand = mongoose.Types.ObjectId(brand);
  }
  if (carModel != "") {
    matchOptions.carModel = mongoose.Types.ObjectId(carModel);
  }
  if (color != "") {
    matchOptions.color = mongoose.Types.ObjectId(color);
  }
  if (fuelType != "") {
    matchOptions.fuelType = mongoose.Types.ObjectId(fuelType);
  }

  var car_list = await Car.aggregate([
    {
      $sort: {
        updatedAt: orderByTime,
      },
    },
    {
      $match: matchOptions,
    },
    {
      $lookup: {
        from: "categories",
        localField: "brand",
        foreignField: "_id",
        as: "brand",
      },
    },
    {
      $lookup: {
        from: "categories",
        localField: "color",
        foreignField: "_id",
        as: "color",
      },
    },
    {
      $lookup: {
        from: "categories",
        localField: "fuelType",
        foreignField: "_id",
        as: "fuelType",
      },
    },
    {
      $lookup: {
        from: "categories",
        localField: "carModel",
        foreignField: "_id",
        as: "carModel",
      },
    },
    {
      $lookup: {
        from: "shops",
        localField: "shopId",
        foreignField: "_id",
        as: "shop",
      },
    },
    // {
    //   $addFields: {
    //     followCount: 0,
    //     signCount: 0,
    //     commitsCount: 0,
    //   },
    // },
    {
      $skip: (currentPage - 1) * pageSize,
    },
    {
      $limit: pageSize,
    },
  ]);

  const total = await Car.where(matchOptions).find().countDocuments();

  res.send({
    car_list: car_list,
    total: total,
  });
});

// 查询用户下所有的车辆
router.get("/car/user/:userId", async (req, res) => {
  // console.log(req.query);
  const currentPage = req.query.currentPage ? Number(req.query.currentPage) : 1;
  const pageSize = req.query.pageSize ? Number(req.query.pageSize) : 10;
  const orderByTime = Number(req.query.orderByTime) == 1 ? 1 : -1;

  matchOptions = {
    userId: mongoose.Types.ObjectId(req.params.userId),
  };

  var car_list = await Car.aggregate([
    {
      $sort: {
        updatedAt: orderByTime,
      },
    },
    {
      $match: matchOptions,
    },
    {
      $lookup: {
        from: "categories",
        localField: "brand",
        foreignField: "_id",
        as: "brand",
      },
    },
    {
      $lookup: {
        from: "categories",
        localField: "color",
        foreignField: "_id",
        as: "color",
      },
    },
    {
      $lookup: {
        from: "categories",
        localField: "fuelType",
        foreignField: "_id",
        as: "fuelType",
      },
    },
    {
      $lookup: {
        from: "categories",
        localField: "carModel",
        foreignField: "_id",
        as: "carModel",
      },
    },
    {
      $lookup: {
        from: "users",
        localField: "userId",
        foreignField: "_id",
        as: "user",
      },
    },
    {
      $lookup: {
        from: "shops",
        localField: "shopId",
        foreignField: "_id",
        as: "shop",
      },
    },
    // {
    //   $addFields: {
    //     followCount: 0,
    //     signCount: 0,
    //     commitsCount: 0,
    //   },
    // },
    {
      $skip: (currentPage - 1) * pageSize,
    },
    {
      $limit: pageSize,
    },
  ]);

  const total = await Car.where(matchOptions).find().countDocuments();

  res.send({
    car_list: car_list,
    total: total,
  });
});

// 查询给定车辆id的信息
router.get("/car/:id", async (req, res) => {
  const model = await Car.findById(req.params.id);
  res.send(model);
});

// =================================================

//获取所有车辆信息
router.get("/getCars", async (req, res) => {
  const model = await Car.find();
  res.send(model);
});

//按id获取车辆详细信息
router.get("/getCarDetails/:id", async (req, res) => {
  const model = await Car.findById(req.params.id);
  res.send(model);
});

//客户上传车辆信息
router.post("/user/upcars", async (req, res) => {
  const model = await Car.create(req.body);
  res.send(model);
});

//carEdit页面查询所需要显示的分类
const Category = require("../../models/Category");

//查找品牌
router.get("/category/brand", async (req, res) => {
  const { _id } = await Category.findOne({ name: "品牌" });
  const model = await Category.find({ parent: _id });
  //console.log(model);
  res.send(model);
});

//查找车型
router.get("/category/carModel", async (req, res) => {
  const { _id } = await Category.findOne({ name: "车型" });
  const model = await Category.find({ parent: _id });
  //console.log(model);
  res.send(model);
});
//查找颜色
router.get("/category/color", async (req, res) => {
  const { _id } = await Category.findOne({ name: "颜色" });
  const model = await Category.find({ parent: _id });
  //console.log(model);
  res.send(model);
});

//查找燃油类型
router.get("/category/fuelType", async (req, res) => {
  const { _id } = await Category.findOne({ name: "燃料类型" });
  const model = await Category.find({ parent: _id });
  // console.log(model);
  res.send(model);
});

//可以接收上传文件的接口
// const multer = require("multer");
// const upload = multer({ dest: __dirname + "/../../uploads" });
// //"上传中间件" 执行multer，写出上传地址
// router.post("/upload", upload.single("file"), async (req, res) => {
//   const file = req.file;
//   //本身是没有req.file因为增加了中间件multer，因此多了这个属性
//   file.url = `http://localhost:3001/uploads/${file.filename}`;
//   res.send(file);
//   //需要一个中间件来处理专门用于上传数据的，multer
//   //singel表示单个文件的上传
// });

module.exports = router;
